package cn.befory.tools;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5 工具类.
 * @author befory
 * @version 1.0
 * @since 2018-07-25
 */
public class MD5Util {

	/** 
     * 获取该输入流的MD5值
     * @since 2018-07-25
     * @param is 输入流
     * @return String
     * @throws NoSuchAlgorithmException  NoSuchAlgorithmException
     * @throws IOException IOException
     */  
    public static String getMD5(InputStream is){
        StringBuffer md5 = new StringBuffer();
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            byte[] dataBytes = new byte[1024];

            int nread = 0;
            while ((nread = is.read(dataBytes)) != -1) {
                md.update(dataBytes, 0, nread);
            };
            byte[] mdbytes = md.digest();
            // convert the byte to hex format
            for (int i = 0; i < mdbytes.length; i++) {
                md5.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return md5.toString();
    }

    /**
     * 获取字符串的的md5值
     * @since 2018-07-25
     * @param str String
     * @return String
     */
    public static String getMD5(String str){
        StringBuffer md5 = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] dataBytes = str.getBytes("utf-8");
            byte[] mdBytes = md.digest(dataBytes);
            for (int i = 0; i < mdBytes.length; i++){
                md5.append(Integer.toString((mdBytes[i] & 0xff) + 0x100, 16).substring(1));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return md5.toString();
    }

//    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//        System.out.println(getMD5("123"));
//    }

}
